<?php
namespace Model;

class Action {
	public function scan() {
		global $o;
		$aFile = $o->File->ls ( ACTION, 'file' );
		$aOldAction = $o->Db->ls ( array (
				'table' => 'actions',
				'key' => 'name' 
		) );
		$o->Db->clear ( 'actions' );
		$o->Db->clear ( 'action_methods' );
		if (is_array ( $aFile )) {
			foreach ( $aFile as $sFile ) {
				$sClassName = basename ( $sFile, '.class.php' );
				$aMethod = $this->_getMethod ( $sFile );
				if ($aMethod) {
					if (is_array ( $aOldAction ['data'] ) && array_key_exists ( $sClassName, $aOldAction ['data'] )) {
						$o->Db->insert ( 'actions', $aOldAction ['data'] [$sClassName] );
					} else {
						$aInfo = array (
								'name' => $sClassName,
								'status' => 'close' 
						);
						$o->Db->insert ( 'actions', $aInfo );
					}
					foreach ( $aMethod as $sMethod => $aDeps ) {
						$aInfo = array (
								'action_name' => $sClassName,
								'method_name' => $sMethod,
								'deps' => serialize ( $aDeps ) 
						);
						$o->Db->insert ( 'action_methods', $aInfo );
					}
				}
			}
		}
		return true;
	}
	
	private function _getMethod($sFile) {
		$sCode = file_get_contents ( $sFile );
		if (preg_match_all ( '/(\/\*\*.+?deps:(.+?)\*.*?\/\s+){0,1}public\s+function\s+(.+?)\(/s', $sCode, $aMatch )) {
			foreach ( $aMatch [3] as $k => $v ) {
				if ($aMatch [2] [$k]) {
					$aDeps = preg_split ( '/[\s,]/s', $aMatch [2] [$k], - 1, PREG_SPLIT_NO_EMPTY );
					foreach ( $aDeps as $sDeps ) {
						list ( $sClass, $sMethod ) = explode ( '::', $sDeps );
						$aData [$v] [$sClass] [] = $sMethod;
					}
				} else {
					$aData [$v] = array ();
				}
			}
			return $aData;
		} else {
			return false;
		}
	}
	
	public function update($aInfo) {
		global $o;
		$aInfo ['status'] = $aInfo ['status'] == 'active' ? 'active' : 'close';
		return $o->Db->update ( 'actions', $aInfo );
	}
	
	public function getTree() {
		global $o;
		$aAction = $o->Db->getArray ( 'actions', 'name', 'name', array (
				'status' => 'active' 
		) );
		$aTree = array ();
		foreach ( $aAction as $sAction ) {
			$aItem = array (
					'id' => $sAction . '::__FULL__',
					'text' => $sAction 
			);
			$aList = $o->Db->ls ( array (
					'table' => 'action_methods',
					'where' => array (
							'action_name' => $sAction 
					) 
			) );
			foreach ( $aList ['data'] as $aRow ) {
				$aItem ['children'] [] = array (
						'id' => $aRow ['action_name'] . '::' . $aRow ['method_name'],
						'text' => $aRow ['action_name'] . '::' . $aRow ['method_name'] 
				);
			}
			$aTree [] = $aItem;
		}
		return $aTree;
	}
}

?>